﻿using FAMailUtils;
using MailBox.App_Code;
using MailBox.App_Code.dto;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MailBox
{
    public partial class SiteMaster : MasterPage
    {
        private const string AntiXsrfTokenKey = "__AntiXsrfToken";
        private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
        private string _antiXsrfTokenValue;

        protected void Page_Init(object sender, EventArgs e)
        {
            // The code below helps to protect against XSRF attacks
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Use the Anti-XSRF token from the cookie
                _antiXsrfTokenValue = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Generate a new Anti-XSRF token and save to the cookie
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;

                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }

            Page.PreLoad += master_Page_PreLoad;
        }

        protected void master_Page_PreLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set Anti-XSRF token
                ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
                ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
            }
            else
            {
                // Validate the Anti-XSRF token
                if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                    || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
                {
                    throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                }
            }
        }
        UserLoginDTO userLogin = null;
        private const string PARAMETER_NAME = "?enc=";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                userLogin = getUserLogin();
                if (userLogin != null)
                {
                    lblUserEmail.Text = hdfSender.Value = Session["EmailLogin"] + "";
                    lblUSerTemp.Text = lblUserEmail.Text;
                    lblUserName.Text = userLogin.isClient ? userLogin.Client.ClientName : userLogin.Account.AccountName;
                    string avatar = userLogin.Account.Avatar;
                    if (string.IsNullOrWhiteSpace(avatar)) avatar = "images/1386966026professional-man.png";
                    master_avatar2.Attributes["src"] = master_avatar.Attributes["src"] = avatar;
                    if (userLogin.Client != null && userLogin.Client.CompanyLogo != "")
                        logo.Attributes["src"] = userLogin.Client.CompanyLogo;
                    if (userLogin.isClient)
                    {

                        string secret = "auto" + Session["EmailLogin"];
                        string EncryptedString = Server.UrlEncode(FaMailUtils.QueryStringModule.Encrypt(secret.Trim()));
                        string url = "http://famails.com/autodirection.aspx";
                        //string url = "http://localhost:51054/autodirection.aspx";
                        hplAutoResponder.NavigateUrl = url + PARAMETER_NAME + EncryptedString;

                        secret = "clie" + Session["EmailLogin"];
                        EncryptedString = Server.UrlEncode(FaMailUtils.QueryStringModule.Encrypt(secret.Trim()));
                        hplClients.NavigateUrl = url + PARAMETER_NAME + EncryptedString;

                        secret = "cust" + Session["EmailLogin"];
                        EncryptedString = Server.UrlEncode(FaMailUtils.QueryStringModule.Encrypt(secret.Trim()));
                        hplCustomer.NavigateUrl = url + PARAMETER_NAME + EncryptedString;

                        secret = "dash" + Session["EmailLogin"];
                        EncryptedString = Server.UrlEncode(FaMailUtils.QueryStringModule.Encrypt(secret.Trim()));
                        hplDashboard.NavigateUrl = url + PARAMETER_NAME + EncryptedString;
                    }
                    CheckMail();
                    string attachfolder = "AttachFiles/" + HttpContext.Current.Session["EmailLogin"];
                    attachfolder = HttpContext.Current.Server.MapPath(attachfolder);
                    decimal size = GetDirectorySize(attachfolder);
                    string limit = "Đã sử dụng được <b>{0} Mb</b> trên tổng <b>300 Mb</b> hạn mức";

                    lblLimit.Text = string.Format(limit, Math.Round(size / 1024 / 1024, 2));

                    int limitsize = 300;
                    int use = (int)Math.Round(Math.Round(size / 1024 / 1024, 2) * 100 / limitsize, 0);
                    if (use < 20) use = 20;
                    usePer.InnerText = Math.Round(Math.Round(size / 1024 / 1024, 2) * 100 / limitsize, 2) + "%";
                    usePer.Attributes["style"] = "height: 17px; background: #d00; float: left; text-align: center; font-size: 12px; font-weight: bold; color: #fff;width:" + use + "%";
                    unusePer.Attributes["style"] = "height: 17px; background: #aaa; float: left; text-align: center; font-size: 12px;width:" + (100 - use) + "%";
                }
            }
        }
        static decimal GetDirectorySize(string attachfolder)
        {
            if (!Directory.Exists(attachfolder)) return 0;
            // 1.
            // Get array of all file names.
            string[] a = Directory.GetFiles(attachfolder, "*.*");

            // 2.
            // Calculate total bytes of all files in a loop.
            decimal b = 0;
            foreach (string name in a)
            {
                // 3.
                // Use FileInfo to get length of each file.
                FileInfo info = new FileInfo(name);
                b += info.Length;
            }
            string[] folders = Directory.GetDirectories(attachfolder);
            foreach (string folder in folders)
            {
                b += GetDirectorySize(folder);
            }
            // 4.
            // Return total size
            return b;
        }
        DataUtils utils = new DataUtils();
        public void CheckMail()
        {
            DataTable table = utils.CheckMail(Session["EmailLogin"] + "");
            int inbox = Convert.ToInt32(table.Compute("sum(mailCount)", "mode=" + (int)InboxType.Inbox));
            int spam = Convert.ToInt32(table.Compute("sum(mailCount)", "mode=" + (int)InboxType.Spam));
            int draft = Convert.ToInt32(table.Compute("sum(mailCount)", "mode=" + (int)InboxType.Drafts));

            if (inbox > 0)
            {
                // Page.Title =
                hplInbox.Text = string.Format("Hộp thư đến({0})", inbox);
                hplInbox.CssClass = "active Showloading";
            }
            else
            {
                //Page.Title =
                hplInbox.Text = "Hộp thư đến";
                //hplInbox.CssClass = "";
            }
            if (spam > 0)
            {
                //Page.Title=
                hplSpam.Text = string.Format("Hộp thư Spam({0})", spam);
                hplSpam.CssClass = "active Showloading";
            }
            else
            {
                //Page.Title =
                hplSpam.Text = "Hộp thư Spam";
                //hplSpam.CssClass = "";
            }
            if (draft > 0)
            {
                //Page.Title =
                hplDraft.Text = string.Format("Thư nháp({0})", draft);
            }
            else
            {
                //Page.Title =
                hplDraft.Text = "Thư nháp";
            }
            table.Dispose();
        }

        private UserLoginDTO getUserLogin()
        {
            userLogin = (UserLoginDTO)Session["UserLogin"];
            if (userLogin == null)
                Response.Redirect("login.aspx", false);
            else return userLogin;
            return null;
        }
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            CheckMail();
        }

        
    }
}